package com.sens.orderback.ui.widget;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Scroller;

import com.sens.orderback.R;

import java.util.LinkedList;
import java.util.List;

public class SwipeBackLayout extends FrameLayout {
    private View contentView;
    private int touchSlop;
    private int downX;
    private int downY;
    private int tempX;
    public Scroller scroller;
    private int viewWidth;
    public boolean isSilding;
    public boolean isFinish;
    private Drawable shadowDrawable;
    private Activity activity;
    private List<ViewPager> viewPagerList = new LinkedList<>();

    public SwipeBackLayout(Activity activity) {
        this(activity, null);
    }

    public SwipeBackLayout(Activity activity, AttributeSet attrs) {
        this(activity, attrs, 0);
    }

    public SwipeBackLayout(Activity activity, AttributeSet attrs, int defStyle) {
        super(activity, attrs, defStyle);
        touchSlop = ViewConfiguration.get(activity).getScaledTouchSlop();
        scroller = new Scroller(activity);
        shadowDrawable = getResources().getDrawable(R.drawable.shadow_left);
        this.activity = activity;
        attachToActivity(activity);
    }

    private void attachToActivity(Activity activity) {
        TypedArray a = activity.getTheme().obtainStyledAttributes(new int[]{android.R.attr.windowBackground});
        int background = a.getResourceId(0, 0);
        a.recycle();
        ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView();
        contentView = decor.getChildAt(0);
        contentView.setBackgroundResource(background);
        decor.removeView(contentView);
        addView(contentView);
        decor.addView(this);
    }

    /**
     * 事件拦截操作
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        // 处理ViewPager冲突问题
        ViewPager mViewPager = getTouchViewPager(viewPagerList, ev);
        if (mViewPager != null && mViewPager.getCurrentItem() != 0) {
            return super.onInterceptTouchEvent(ev);
        }
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = tempX = (int) ev.getRawX();
                downY = (int) ev.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int moveX = (int) ev.getRawX();
                // 满足此条件屏蔽SildingFinishLayout里面子类的touch事件
                if (downX > 100) {
                    return false;
                }

                if (moveX - downX > touchSlop && Math.abs((int) ev.getRawY() - downY) < touchSlop) {
                    return true;
                }
                break;
        }
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                int moveX = (int) event.getRawX();
                int deltaX = tempX - moveX;
                tempX = moveX;
                if (moveX - downX > touchSlop && Math.abs((int) event.getRawY() - downY) < touchSlop) {
                    isSilding = true;
                }

                if (moveX - downX >= 0 && isSilding) {
                    contentView.scrollBy(deltaX, 0);
                }
                break;
            case MotionEvent.ACTION_UP:
                isSilding = false;
                if (contentView.getScrollX() <= -viewWidth / 3) {// 滑动的距离判断
                    isFinish = true;
                    scrollRight();
                } else {
                    scrollOrigin();
                    isFinish = false;
                }
                break;
        }
        return true;
    }

    /**
     * 获取SwipeBackLayout里面的ViewPager的集合
     *
     * @param mViewPagers
     * @param parent
     */
    private void getAlLViewPager(List<ViewPager> mViewPagers, ViewGroup parent) {
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
            if (child instanceof ViewPager) {
                mViewPagers.add((ViewPager) child);
            } else if (child instanceof ViewGroup) {
                getAlLViewPager(mViewPagers, (ViewGroup) child);
            }
        }
    }

    /**
     * 返回我们touch的ViewPager
     *
     * @param viewPagerList
     * @param ev
     * @return
     */
    private ViewPager getTouchViewPager(List<ViewPager> viewPagerList, MotionEvent ev) {
        if (viewPagerList == null || viewPagerList.size() == 0) {
            return null;
        }
        Rect rect = new Rect();
        for (ViewPager viewPager : viewPagerList) {
            viewPager.getHitRect(rect);
            if (rect.contains((int) ev.getX(), (int) ev.getY())) {
                return viewPager;
            }
        }
        return null;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (changed) {
            viewWidth = this.getWidth();
            getAlLViewPager(viewPagerList, this);
        }
    }

    private static DisplayMetrics displaysMetrics = null;
    private static float scale = -1.0f;

    private DisplayMetrics getDisplayMetrics() {
        if (null == displaysMetrics) {
            displaysMetrics = new DisplayMetrics();
            WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
            wm.getDefaultDisplay().getMetrics(displaysMetrics);
        }
        return displaysMetrics;
    }

    private float dip2px(float dpValue) {
        if (scale < 0) {
            if (null == displaysMetrics) {
                getDisplayMetrics();
            }
            scale = displaysMetrics.density;
        }
        return dpValue * scale + 0.5f;
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        if (contentView != null) {
            int right = -contentView.getScrollX();
            int left = (int) (right - dip2px(10));
            int top = contentView.getTop();
            int bottom = contentView.getBottom();
            shadowDrawable.setBounds(left, top, right, bottom);
            shadowDrawable.draw(canvas);
        }
    }

    /**
     * 滚动出界面
     */
    private void scrollRight() {
        final int delta = (viewWidth + contentView.getScrollX());
        // 调用startScroll方法来设置一些滚动的参数，我们在computeScroll()方法中调用scrollTo来滚动item
        scroller.startScroll(contentView.getScrollX(), 0, -delta + 1, 0, Math.abs(delta));
        postInvalidate();
    }

    /**
     * 滚动到起始位置
     */
    private void scrollOrigin() {
        int delta = contentView.getScrollX();
        scroller.startScroll(contentView.getScrollX(), 0, -delta, 0, Math.abs(delta));
        postInvalidate();
    }

    @Override
    public void computeScroll() {
        if (scroller.computeScrollOffset()) {
            contentView.scrollTo(scroller.getCurrX(), scroller.getCurrY());
            postInvalidate();
            if (scroller.isFinished() && isFinish) {
                activity.finish();
            }
        }
    }
}
